package com.hycreate.platform.modules.product;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.hycreate.platform.common.config.Config;
import com.hycreate.platform.common.config.Global;
import com.hycreate.platform.common.persistence.Page;
import com.hycreate.platform.common.utils.FileUtils;
import com.hycreate.platform.common.utils.StringUtils;
import com.hycreate.platform.common.utils.excel.ImportExcel;
import com.hycreate.platform.common.utils.mypage.PageDemo;
import com.hycreate.platform.common.utils.mypage.PageDemoUtil;
import com.hycreate.platform.common.web.BaseController;
import com.hycreate.platform.modules.atta.SfAttachment;
import com.hycreate.platform.modules.atta.SfAttachmentService;
import com.hycreate.platform.modules.product.element.SfProductElement;
import com.hycreate.platform.modules.project.product.SfProjectProduct;
import com.hycreate.platform.modules.sys.utils.UserUtils;

/**
 * 产品Controller
 * @author hoader
 * @version 2017-01-09
 */
@Controller
@RequestMapping(value = "${adminPath}/product/sfProduct")
public class SfProductController extends BaseController {

	@Autowired
	private SfProductService sfProductService;
	
	@Autowired
	private SfAttachmentService sfAttachmentService;
	
	@ModelAttribute
	public SfProduct get(@RequestParam(required=false) String id) {
		SfProduct entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = sfProductService.get(id);
		}
		if (entity == null){
			entity = new SfProduct();
		}
		return entity;
	}
	
	@RequiresPermissions("product:sfProduct:view")
	@RequestMapping(value = {"list", ""})
	public String list(SfProduct sfProduct, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		 Page<SfProduct> page = sfProductService.findPage(new Page<SfProduct>(request, response), sfProduct); 
		 model.addAttribute("page", page);
	       	
		 return "modules/product/sfProductList";
	}

	@RequiresPermissions("product:sfProduct:view")
	@RequestMapping(value = "projectproductlist")
	public String projectproductlist(SfProduct sfProduct, Model model,HttpServletRequest request, HttpServletResponse response) {
		
		    int everyPage=30; //每页30条
			int current=0;
		    String temp=request.getParameter("current");
			if(temp!=null){
				 current=Integer.parseInt(temp);
			} 
			 String type= request.getParameter("type");
		
		     String pid=request.getParameter("pid");
		     
		

			 int total= sfProductService.ProductEntityCount(pid);
			 int totalPages=PageDemoUtil.Comparison(total,everyPage); //总页数
			 PageDemo pd=PageDemoUtil.Calculation(total, current, type,everyPage);
			 
		
			 pd.setValueId(pid);
			    
			 List<SfProduct> list= sfProductService.ProductEntityPage(pd); 
			 
			 System.out.println("---------"+list.size());
			// 把数据传回前台
			model = Paging(model, current, total, type, everyPage);
	
            model.addAttribute("list", list);
            
            model.addAttribute("tp", totalPages);
		
		
		
		return "modules/product/ProjectProductList";
	}
	
	
	
	@RequiresPermissions("product:sfProduct:view")
	@RequestMapping(value = "form")
	public String form(SfProduct sfProduct, Model model) {
		model.addAttribute("sfProduct", sfProduct);
		return "modules/product/sfProductForm";
	}

	@RequiresPermissions("product:sfProduct:edit")
	@RequestMapping(value = "save")
	public String save(SfProduct sfProduct, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, sfProduct)){
			return form(sfProduct, model);
		}
		sfProductService.save(sfProduct);
		addMessage(redirectAttributes, "保存产品成功");
		return "redirect:"+Global.getAdminPath()+"/product/sfProduct/?repage";
	}
	
	@RequiresPermissions("product:sfProduct:edit")
	@RequestMapping(value = "delete")
	public String delete(SfProduct sfProduct, RedirectAttributes redirectAttributes) {
		
		List<String> delList = new ArrayList<String>();
		delList.add(sfProduct.getId());
		
		sfProductService.delete(sfProduct);
		
		sfProductService.DeletesRedundancy(delList);
		
		sfProductService.DeletesRedundancyProduct(delList);
		
		addMessage(redirectAttributes, "删除产品成功");
		return "redirect:"+Global.getAdminPath()+"/product/sfProduct/?repage";
	}

	/**
	 * 导入项目图片
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("product:sfProduct:edit")
    @RequestMapping(value = "importPic", method=RequestMethod.POST)
    public String importPic(MultipartFile mfile, HttpServletRequest request, RedirectAttributes redirectAttributes) {
		
		/**
		 * 文件存储路径
		 */
		StringBuffer unZipCopyPath = new StringBuffer(request.getSession().getServletContext().getRealPath("/"));
		unZipCopyPath.append("userfiles/").append(UserUtils.getUser().getId()).append("/product/images/").append("XXX");
		
		/**
		 * 文件访问路径
		 */
		StringBuffer urlBuffer = new StringBuffer();
		urlBuffer.append(request.getContextPath());
		urlBuffer.append("/userfiles/").append(UserUtils.getUser().getId()).append("/product/images/");
		
		int successNum = 0;//成功数
		int failureNum = 0;//失败数
		
		StringBuilder failureMsg = new StringBuilder();
		String descDir = Config.getConfig("unZip.product.pic");
		FileUtils.createDirectory(descDir);
		String upFilePath = descDir + "/" + mfile.getOriginalFilename();
		try {
			mfile.transferTo(new File(upFilePath));
			
			this.unZip(descDir + "/", upFilePath);
			
			String unzipPath = descDir + "/" + mfile.getOriginalFilename().split("\\.")[0];
			File descDirFile = new File(unzipPath);
			String[] fileNames = descDirFile.list();
			FilenameFilter filter=new FilenameFilter() {  
	            @Override  
	            public boolean accept(File dir, String name) {
	            	name = name.toLowerCase();
	                return name.endsWith(".jpg") || name.endsWith(".png");  
	            }  
	        };
			
	        SfProduct sfProduct;
			SfAttachment sfAttachment;
			List<SfProduct> sfProjectList = null;
			for(String fileName : fileNames){
				if (fileName.split("\\.").length < 1) {
					continue;
				}
				
				 String pic=fileName.substring(0,fileName.lastIndexOf("."));
				
				sfProduct = new SfProduct();
				
				sfProduct.setCode(pic);
				sfProjectList = sfProductService.findList(sfProduct);
				if(CollectionUtils.isEmpty(sfProjectList)){
					failureMsg.append("<br/>产品"+fileName+"不存在！; ");
					failureNum++;
					continue;
				}
					sfProduct = sfProjectList.get(0);
					
					File descDirPicFile = new File(unzipPath+ "/" + fileName);
					
						FileUtils.copyFile(descDirPicFile.getAbsolutePath(), unZipCopyPath.toString().replace("XXX", fileName));
						sfAttachment = new SfAttachment();
						sfAttachment.setObjectId(sfProduct.getId());
						sfAttachment.setUrl(urlBuffer.toString() + descDirPicFile.getName());
						sfAttachmentService.save(sfAttachment);
						
						sfProduct.setExistImage("已有");
						sfProductService.save(sfProduct);
						
						
					successNum++;
				}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条产品，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条产品"+failureMsg);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		FileUtils.deleteDirectory(descDir);
		return "redirect:" + adminPath + "/product/sfProduct/list?repage";
	}
	
	@RequiresPermissions("product:sfProduct:view")
	@RequestMapping(value = "batchDeletes")
	public void batchDeletes( HttpServletRequest request,
			HttpServletResponse response, Model model) {
		
		List<String> delList = batch_deletion(request);

		try {
			sfProductService.batchDeletes(delList);
			
			sfProductService.DeletesRedundancy(delList);
			
			sfProductService.DeletesRedundancyProduct(delList);
			
		} catch (Exception e) {
			logger.error("删除失败");

		}
		
		
		
	}
	
	/**
	 * 删除项目产品表中的冗余数据
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("element:sfElement:view")
	@RequestMapping(value = "deletesAssociation")
	public String  deletesAssociation( HttpServletRequest request,
			HttpServletResponse response, Model model) {
	  
	   List<String> delList = new ArrayList<String>();
		
	   List<SfProjectProduct>  list=sfProductService.DELLIST();
		
	    System.out.println(list.size()); 
	    
	    for (SfProjectProduct sfProjectProduct : list) {
			
	    	delList.add(sfProjectProduct.getId());
		}
		
	    try {
	    	sfProductService.DeletesRedundancyProduct(delList);
		} catch (Exception e) {
			
			logger.error("删除失败");
		}
		
		return "modules/product/sfProductList";
	}
	
	
	
	@RequiresPermissions("product:sfProduct:view")
	@RequestMapping(value = "updateimport", method = RequestMethod.POST)
	public String importProjectFile(MultipartFile file,
			RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 0, 0);
			List<UpdateProductImport> list = ei.getDataList(UpdateProductImport.class);

			SfProduct sfProduct = null;
			SfProjectProduct sfProjectProduct;
			List<SfProduct> sfProductList = null;
			List<SfProjectProduct> sfProjectProductList = null;
			int i = 0;
			
			for (UpdateProductImport updateproduct : list) {
				try {
					boolean isFlag = false;

					sfProduct=null;
					/**
					 * 项目编号为空，为无效数据
					 */
					if (StringUtils.isEmpty(updateproduct.getProductCode()
							.trim())) {
						failureMsg.append("<br/>项目编号为空，为无效数据; ");
						continue;
					}
					 if(StringUtils.isNotEmpty(updateproduct.getShipMentCount().trim())){
					
					sfProduct = new SfProduct();
					
				
					
					sfProduct.setCode(updateproduct.getProductCode().trim());
					
					sfProductList = sfProductService.findImportList(sfProduct);
					
					if (CollectionUtils.isEmpty(sfProductList)) {
						failureMsg.append("<br/>产品编号不存在，为无效数据; ");
						continue;
					} else {
						
						 if(sfProductList.size()==1){
							
							 
							 sfProduct= sfProductList.get(0);
							 
							 sfProduct.setAge(updateproduct.getAge().trim());
								
							 sfProduct.setStatus(updateproduct.getStatus().trim());
							 
							 sfProduct.setShipMentCount(updateproduct.getShipMentCount().trim());
							 
							 sfProductService.save(sfProduct);
							 
							 isFlag = true;
							 
						 }
						
					}
				 }
					if (isFlag) {
						successNum++;
					} else {
						failureMsg.append("<br/>无效数据; " + i);
					}
				

				} catch (Exception e) {
					e.printStackTrace();
					failureNum++;
				}
				i++;
			}
			if (failureNum > 0) {
				failureMsg.insert(0, "，失败 " + failureNum + " 条项目，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功更新 " + successNum + " 条数据"
					+ failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "更新数据失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + adminPath + "/product/sfProduct/list?repage";
	}
	
	
	
	@SuppressWarnings("rawtypes")
	private void unZip(String descDir, String upFilePath) throws IOException {
		ZipFile zip = new ZipFile(upFilePath, "GBK");
		for (Enumeration entries = zip.getEntries(); entries.hasMoreElements();) {
			ZipEntry entry = (ZipEntry) entries.nextElement();
			String zipEntryName = entry.getName();
			InputStream in = zip.getInputStream(entry);
			String outPath = (descDir + zipEntryName).replaceAll("\\*", "/");
			// 判断路径是否存在,不存在则创建文件路径
			File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
			if (!file.exists()) {
				file.mkdirs();
			}
			// 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
			if (new File(outPath).isDirectory()) {
				continue;
			}
			// 输出文件路径信息
			logger.debug(outPath);

			OutputStream out = new FileOutputStream(outPath);
			byte[] buf1 = new byte[1024];
			int len;
			while ((len = in.read(buf1)) > 0) {
				out.write(buf1, 0, len);
			}
			in.close();
			out.close();
		}
		zip.close();
		logger.debug("******************解压完毕********************");
	}
	
	/**
	 * 
	 * batch_deletion:(批量删除，把前台的字符串截取为list对象)
	 * 
	 * @param request
	 * @return 返回删除的集合
	 */
	private List<String> batch_deletion(HttpServletRequest request) {
		
		String items = request.getParameter("delitems");

		List<String> delList = new ArrayList<String>();
		
		String[] strs = items.split(",");
		for (String str : strs) {
			delList.add(str);
		}
		return delList;  
	}
	
	
	
	
	
	
	// 返回的页数的方法
		private Model Paging(Model model, int current, int total, String type,
				int everyPage) {
			if(type==null){
				return model.addAttribute("current", 1);	
			}
			
			if (type.equals("hasPrePage")) {

				if (current > 1) {
					return model.addAttribute("current", current);
				} else {
					return model.addAttribute("current", 1);
				}

			} else if (type.equals("hasNextPage")) {
				if (current < PageDemoUtil.Comparison(total, everyPage)) {
					return model.addAttribute("current", current);
				} else {
					return model.addAttribute("current",
							PageDemoUtil.Comparison(total, everyPage));
				}
			} else if (type.equals("startPage")) {
				
				return model.addAttribute("current", 1);
			} else if (type.equals("endPage")) {
				return model.addAttribute("current",
						PageDemoUtil.Comparison(total, everyPage));
			} else if (type.equals("pagenumb")) {

				return model.addAttribute("current", current);
			} else {

				return model;
			}

		}
	
}